<?php
declare(strict_types=1);

namespace Service\ChannelService;

use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\OrderReturn;
use App\Model\BbcModel\MnWithdraw;
use App\Model\BbcModel\Mnuser;
use App\Model\BbcModel\MnChannel;
use App\Model\BbcModel\Order;
use App\Model\BbcModel\Decorate;
use App\Model\BbcModel\DecorateDetail;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\Specialtopic;
use App\Model\BbcModel\SpecialtopicGoods;
use App\Model\BbcModel\GoodsTags;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\MnStoreAdv;
use App\Model\BbcModel\DecorateTab;
use App\Model\BbcModel\Message;
use App\Model\BbcModel\OrderChannel;
use App\Model\BbcModel\OrderGoods;
use Service\HelperService\Common;
use Service\CacheService\CacheProviderService as Cache;
use Service\ConfigureService\ChannelConfigService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Database\Model\Collection;

/**
 * TO C/B SBBC渠道分销
 * @author hj
 */
class ChannelService extends BaseService {
    //每页条数
    protected $page = 1;
    //每页条数
    protected $limit = 10;

    /**
     * 渠道分销首页数据
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getChannelInfo(array $param) {
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $user = MnChannel:: where('id', (int)($param['cid']))->where('status', 1)->where('check_status', 1)->first();
        if (empty($user)) {
            return Normal::returnCode(Normal::FAIL, '渠道不存在');
        }
        $result['qrcode']        = $user->qrcode;
        $result['wallet_income'] = $user->wallet_income;//累计总收益。
        $result['frozen_income'] = $user->frozen_income;//待确认收益
        $channelMoneyInfo        = ChannelWxService::getChannelMoney(['channel_id' => $user->id]);
        if ($channelMoneyInfo['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::FAIL, $channelMoneyInfo['msg']);
        }
        $result['pre_money']        = $channelMoneyInfo['data']['show_money'];
        $orderFields                = ['id', 'status', 'pay_status', 'price_order', 'channel_money', 'cd'];
        $orderAll                   = Order::where('cid', $user->id)->where('pay_status', 1)->where('status', '>', 0)->where('sid', getSID())->orderBy('id', 'desc')->select($orderFields)->get();
        $orderToday                 = $orderAll->where('cd', '>', strtotime(date('Ymd')))->toArray();
        $result['today_sell']       = round(array_sum(array_column($orderToday, 'price_order')), 2);
        $result['today_number']     = count($orderToday);
        $result['today_distribute'] = round(array_sum(array_column($orderToday, 'channel_money')), 2);
        $orderAllArr                = $orderAll->toArray();
        $result['all_sell']         = round(array_sum(array_column($orderAllArr, 'price_order')), 2);
        $result['all_number']       = count($orderAllArr);
        $result['all_distribute']   = round(array_sum(array_column($orderAllArr, 'channel_money')), 2);
        $result['order_return']     = OrderReturn::where('cid', $user->id)->where('check_status', 0)->where('sid', getSID())->count();
        $result['withdraw_number']  = MnWithdraw::where('cid', $user->id)->where('check_status', 0)->where('sid', getSID())->count();
        $orderMonth                 = $orderAll->where('cd', '>', strtotime(date('Y-m', time())))->toArray();
        $result['month_sell']       = round(array_sum(array_column($orderMonth, 'price_order')), 2);
        $result['month_number']     = count($orderMonth);
        $time                       = time() - 86400;
        $result['no_shipping']      = $orderAll->where('cd', '<', $time)->where('status', 20)->count();
        return Normal::returnCode(Normal::SUC, '获取成功', $result);
    }

    /**
     * 分销用户，下游Q店
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getStore(array $param) {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        $user = MnChannel::where('mid', (int)($param['mid']))->where('status', 1)->where('check_status', 1)->first();
        if (empty($user)) {
            return Normal::returnCode(Normal::FAIL, '请先开通渠道');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $mnModel = Mnuser::where('pid', $user->id)->where('status', 1)->where('new_store', 1);
        if (isset($param['key_word']) && !empty($param['key_word'])) {
            $keyWord = $param['key_word'];
            $mnModel = $mnModel->where(function ($query) use ($keyWord) {
                $query->orWhere('store_name', 'like', "%{keyWord}%")->orWhere('account', 'like', "%{keyWord}%");
            });
        }
        $result = $mnModel->select(['id', 'account', 'store_name', 'img'])->orderBy('id', 'desc')->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功');
        }
        $collection      = $result->getCollection();
        $mn_sids         = $collection->pluck('id')->toArray();
        $orderAllByMnsid = [];
        $orderAll        = order::whereIn('mn_sid', $mn_sids)->where('pay_status', 1)->where('status', '>', 0)->select(['price_order', 'mn_sid'])->get()->toArray();
        if ($orderAll) {
            foreach ($orderAll as $item) {
                $orderAllByMnsid[$item['mn_sid']][] = $item;
            }
        }
        $collection->each(function ($item, $key) use ($orderAllByMnsid) {
            $order              = $orderAllByMnsid[$item->id] ?? [];
            $item->order_number = count($order);
            $item->order_money  = $order ? round(array_sum(array_column($order, 'price_order')), 2) : 0.00;
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', $collection->toArray());
    }

    /**
     * 小b分享配置
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getShare(array $param) {
        $b2b = ChannelConfigService::instance()->getConfig(['cid' => $param['cid'], 'code' => 'b2b_share']);
        if ($b2b['code'] != Normal::SUC) {
            return $b2b;
        }
        $b2b_share              = $b2b['data']['value'] ?? [];
        $share['b_store_title'] = $b2b_share['title'] ?? '';
        $share['b_cover']       = $b2b_share['img'] ?? '';
        return Normal::returnCode(Normal::SUC, '获取成功', $share);
    }

    /**
     * 渠道小程序banner
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function banner(array $param) {
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $param['cid'] = (int)($param['cid']);
        $res          = Decorate::where('type', 2)->where('cid', $param['cid'])->first();
        if (!$res) {
            $banner = [['img_url' => Decorate::DEFAULT_IMG_URL_1], ['img_url' => Decorate::DEFAULT_IMG_URL_2]];
            return Normal::returnCode(Normal::SUC, '内容为空', ['banner' => $banner, 'banner_height' => 240]);
        }
        $res              = $res->toArray();
        $banner           = DecorateDetail::where('decorate_id', $res['id'])->where('type', 1)->select(['img_url', 'object_type', 'object_id'])->get();
        $bannerCollection = $banner;
        $banner           = $banner->toArray();
        if (!$banner) {
            $banner = [['img_url' => Decorate::DEFAULT_IMG_URL_1], ['img_url' => Decorate::DEFAULT_IMG_URL_2]];
        } else {
            $class_ids         = $bannerCollection->where('object_type', 3)->pluck('object_id')->toArray();
            $special_topic_ids = $bannerCollection->where('object_type', 2)->pluck('object_id')->toArray();
            $goodsclassAll     = GoodsClass::whereIn('id', $class_ids)->pluck('name', 'id')->toArray();
            $specialtopicAll   = Specialtopic::whereIn('id', $special_topic_ids)->select(['status', 'id'])->get()->toArray();
            if ($specialtopicAll) {
                $specialtopicAll = array_column($specialtopicAll, null, 'id');
            }
            foreach ($banner as $k => &$v) {
                if (!$v['img_url']) {
                    unset($v);
                    continue;
                }
                if (!$v['object_id']) {
                    unset($v['object_type']);
                    unset($v['object_id']);
                    continue;
                }
                if ($v['object_type'] == 3) {
                    $v['column_name'] = $goodsclassAll[$v['object_id']] ?? '';
                }
                if ($v['object_type'] == 2) {
                    $specialtopic = $specialtopicAll[$v['object_id']] ?? [];
                    if ($specialtopic) {
                        //专题馆下架
                        if ($specialtopic['status'] == 0) {
                            // $banner[$k]['object_id'] = 0;
                            unset($v['object_type']);
                            unset($v['object_id']);
                        }
                    }
                }
            }
            unset($v);
        }
        //专题馆
        $goodsFields = [
            'id', 'name', 'img', 'price_recommend', 'price_cost', 'skucode', 'barcode', 'is_bonded', 'price_store as price', 'status', 'price_cost',
            'num_storage', 'price_market', 'fictitious_sale', 'num_sale', 'is_trade', 'supply_tag', 'tag'
        ];
        $topicGoods  = [];
        $object_ids  = DecorateDetail::where('decorate_id', $res['id'])->where('type', 2)->where('type', 1)->orderByRaw('show_order desc,md desc')->pluck('object_id')->toArray();
        if ($object_ids) {
            $showTag              = GoodsTags::where('cid', $param['cid'])->where('show', 1)->select(['id', 'show_name', 'img', 'position'])->get()->toArray();
            $topicCollection      = Specialtopic::whereIn('id', $object_ids)->where('status', 1)->where('df', 0)->get();
            $topicAll             = $topicCollection->toArray();
            $specialtopic_ids     = $topicCollection->pluck('id')->toArray();
            $allSpGoodsByGoodsIds = [];
            $allGoodsIds          = [];
            $allSpGoods           = SpecialtopicGoods::whereIn('specialtopic_id', $specialtopic_ids)->where('df', 0)->select(['goods_id', 'specialtopic_id'])->get()->toArray();
            if ($allSpGoods) {
                foreach ($allSpGoods as $allSpGood) {
                    $allSpGoodsByGoodsIds[$allSpGood['specialtopic_id']][] = $allSpGood;
                    array_push($allGoodsIds, $allSpGood['goods_id']);
                }
            }
            $allGoodsIds = $allGoodsIds ? array_unique($allGoodsIds) : [];
            $allGoodsCol = collect([]);
            if ($allGoodsIds) {
                $allGoodsCol = Goods::whereIn('id', $allGoodsIds)->where('df', 0)->where('status', 1)->where('is_trade', 0)->where('cid', $param['cid'])->where('is_recommend', '<>', 0)->orderBy('is_recommend', 'desc')->select($goodsFields)->get();
            }
            foreach ($object_ids as $object_id) {
                $topic = $topicAll[$object_id] ?? [];
                if (!empty($topic)) {
                    $goods_ids_Arr = $allSpGoodsByGoodsIds[$topic['id']] ?? [];
                    $goods_ids     = $goods_ids_Arr ? array_column($goods_ids_Arr, 'goods_id') : [];
                    $goods         = [];
                    if ($allGoodsCol->isNotEmpty() && $goods_ids) {
                        $goods = $allGoodsCol->whereIn('id', $goods_ids)->take(7)->toArray();
                    }
                    foreach ($goods as $key => $value) {
                        $goods[$key]['label'] = [];
                        if (!empty($showTag)) {
                            $tags = [];
                            if (!empty($value['tag'])) {
                                $tags = explode(',', $value['tag']);
                            }
                            if (!empty($value['supply_tag'])) {
                                $tags = array_merge($tags, explode(',', $value['supply_tag']));
                            }
                            if (!empty($tags)) {
                                foreach ($showTag as $item) {
                                    if (in_array($item['id'], $tags)) {
                                        $goods[$key]['label'][] = $item;
                                    }
                                }
                            }
                        }
                    }
                    $row          = [
                        'topic' => [
                            'id'   => $topic['id'],
                            'name' => $topic['name'],
                            'img'  => $topic['pic'],
                        ],
                        'goods' => $goods
                    ];
                    $topicGoods[] = $row;
                }
            }
        }
        $goods = [];
        $title = '';
        if (isset($res['title']) && $res['title']) {
            $title = $res['title'];
            $goods = Goods::where('df', 0)->where('status', 1)->where('is_trade', 0)->where('cid', $param['cid'])->where('is_recommend', '<>', 0)->orderBy('show_order', 'desc')->select($goodsFields)->get()->toArray();
        }
        $returnData['banner']        = array_values($banner);
        $returnData['banner_height'] = $res['banner_height'] ?? 240;
        $returnData['specialtopic']  = $topicGoods;
        $returnData['column']        = ['title' => $title, 'goods_lists' => $goods];
        return ['status' => Normal::SUC, 'msg' => '获取成功', 'data' => $returnData];
    }

    /**
     * 首页推荐栏标题及商品
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function choiceGoodsLists(array $param) {
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $param['cid'] = (int)($param['cid']);
        $template     = Decorate::where('type', 2)->where('cid', $param['cid'])->first();
        if (!$template) {
            return Normal::returnCode(Normal::SUC, '推荐栏商品为空', ['title' => '', 'goods_lists' => []]);
        }
        if (empty($template->title)) {
            return Normal::returnCode(Normal::SUC, '推荐栏商品为空', ['title' => '', 'goods_lists' => []]);
        }
        $fields = [
            'id', 'name', 'img', 'price_recommend', 'price_cost', 'skucode', 'barcode', 'is_bonded', 'price_store as price',
            'status', 'num_storage', 'price_market', 'fictitious_sale', 'num_sale', 'is_trade'
        ];
        $goods  = Goods::where('is_recommend', '<>', 0)->where('df', 0)->where('status', 1)->where('cid', $param['cid'])->orderByRaw('is_recommend desc,id desc')->select($fields)->paginate($this->limit, ['*'], 'page', $this->page);
        if ($goods->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '请求成功', ['title' => '', 'goods_lists' => []]);
        }
        return Normal::returnCode(Normal::SUC, '请求成功', ['title' => $template['title'], 'goods_lists' => $goods->items()]);
    }

    /**
     * 小B首页内容（banner/组件）
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function homePage(array $param) {
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        $param['cid'] = (int)($param['cid']);
        $info         = [];
        //小B
        if ($param['mnid'] == 2) {
            if (isset($param['mn_sid']) && $param['mn_sid'] == 0) {
                //后台预览
                $template = Decorate::where('cid', $param['cid'])->where('type', 2)->where('id', $param['adv_temp'])->first();
            } else {
                $template = Decorate::where('cid', $param['cid'])->where('type', 2)->where('df', 0)->where('is_default', 1)->first();
            }
        } else {
            //店铺
            $adv_temp = Mnuser::where('id', $param['mn_sid'])->value('adv_temp');
            $template = Decorate::where('id', $adv_temp)->where('df', 0)->first();
        }
        if (!$template) {
            return MnStoreAdv::defaultTemplate($param);
        }
        $template  = $template->toArray();
        $fields    = ['id', 'title', 'color', 'banner_height', 'page_spacing', 'edges_type', 'top_spacing', 'bottom_spacing'];
        $tab_lists = DecorateTab::where('decorate_id', $template['id'])->orderByRaw('show_order asc,id asc')->select(['id', 'title'])->get()->toArray();
        if (!$tab_lists) {
            return MnStoreAdv::defaultTemplate($param);
        }
        $result['background_type'] = $template['background_type'];
        $result['image']           = $template['image'];
        $result['bgcolor']         = empty($template['bgcolor']) ? '#F27180' : $template['bgcolor'];
        $result['tabbgcolor']      = empty($template['tabbgcolor']) ? '#B77559' : $template['tabbgcolor'];
        $result['font_color']      = empty($template['font_color']) ? '#FFF' : $template['font_color'];
        $result['is_goods_lists']  = $template['is_goods_lists'];
        $result['is_class_nav']    = $template['is_class_nav'];
        $result['notice_type']     = $template['notice_type'];
        $result['notice_position'] = $template['notice_position'];
        $result['notice_img']      = $template['notice_img'];
        $result['tab_lists']       = $tab_lists;
        $message_red               = 0;
        if ($param['mid']) {
            $message_read = Message::query()->from((new Message)->getTable() . ' as m')->leftJoin("ly_message_user_click as mc", 'm.id', '=', 'mc.message_id')
                ->where('mc.mid', $param['mid'])->where('m.status', 1)->where('m.cid', $param['cid'])->where('m.df', 0)->where('m.type', 0)->count();
            $allmessage   = Message::where('status', 1)->where('cid', $param['cid'])->where('df', 0)->where('type', 0)->count();
            if ($allmessage > $message_read) {
                $message_red = 1;
            }
        }
        $result['message_red'] = $message_red;
        return Normal::returnCode(Normal::SUC, '获取成功', $result);
    }

    /**
     * 设置自动上架
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function autoUp(array $param) {
        $check = Mnuser::validate($param);
        if ($check['code'] != Normal::SUC) {
            return $check;
        }
        $has = $check['data'];
        if (!isset($param['status']) || !in_array($param['status'], ['0', '1'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument status');
        }
        Mnuser::where('id', $has['id'])->update(['auto_up' => $param['status'], 'md' => time()]);
        return Normal::returnCode(Normal::SUC, '设置成功');
    }

    /**
     * 添加历史进货单
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function addHistoryOrder(array $param) {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (!isset($param['sn']) || empty($param['sn'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument sn');
        }
        $order = Order::where('cid', (int)($param['cid']))->where('sn', $param['sn'])->where('mid', (int)($param['mid']))->first();
        if (empty($order)) {
            return Normal::returnCode(Normal::FAIL, '订单不存在');
        }
        $order_list = Order::where('pay_sn', $order->pay_sn)->select(['id', 'sn', 'is_bonded'])->get();
        if ($order_list->isEmpty()) {
            return Normal::returnCode(Normal::FAIL, '此订单没有可加入历史进货单的子订单');
        }
        $order_ids       = $order_list->pluck('id')->toArray();
        $order_list      = $order_list->toArray();
        $allOrderChannel = OrderChannel::whereIn('order_id', $order_ids)->where('mid', (int)($param['mid']))->select(['id', 'order_id'])->get()->toArray();
        if ($allOrderChannel) {
            $allOrderChannel = array_column($allOrderChannel, null, 'order_id');
        }
        $new_order = [];
        foreach ($order_list as $key => $val) {
            $has = $allOrderChannel[$val['id']] ?? [];
            if ($has) {
                continue;
            }
            if ($val['is_bonded'] == 1) {
                continue;
            }
            $new_order[] = $val;
        }
        if (!$new_order) {
            return Normal::returnCode(Normal::FAIL, '此订单没有可加入历史进货单的子订单');
        }
        $num = OrderChannel::where('mid', (int)($param['mid']))->count();
        if ($num == 0) {
            $num = 1;
        }
        $addData = [];
        $curTsp  = time();
        foreach ($new_order as $k => $v) {
            $addData[] = [
                'name'     => '默认进货单' . $num,
                'mid'      => $param['mid'],
                'order_id' => $v['id'],
                'sn'       => $v['sn'],
                'cid'      => $param['mid'],
                'cd'       => $curTsp,
                'sid'      => getSID(),
            ];
            $num++;
        }
        try {
            $result = OrderChannel::insert($addData);
            if (!$result) {
                throw new \RuntimeException("添加失败");
            }
        } catch (\Throwable $th) {
            return Normal::returnCode(Normal::FAIL, $th->getMessage());
        }
        return Normal::returnCode(Normal::SUC, '加入成功');
    }

    /**
     * 历史进货单列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function historyOrderList(array $param) {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['cid']) || empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument cid');
        }
        if (isset($param['page']) && ctype_digit((string)$param['page']) && $param['page'] > 0) {
            $this->page = $param['page'];
        }
        if (isset($param['limit']) && ctype_digit((string)$param['limit']) && $param['limit'] > 0) {
            $this->limit = $param['limit'];
        }
        $fields = ['oc.id as history_id', 'oc.sn', 'oc.order_id', 'o.price_order', 'oc.name', 'o.goods_num'];
        $result = OrderChannel::query()->from((new OrderChannel)->getTable() . ' as oc')->leftJoin("ly_order as o", 'o.id', '=', 'oc.order_id')
            ->where('oc.mid', $param['mid'])->where('o.is_bonded', '<>', 2)->select($fields)->orderByRaw('oc.cd desc,oc.id desc')
            ->paginate($this->limit, ['*'], 'page', $this->page);
        if ($result->isEmpty()) {
            return Normal::returnCode(Normal::SUC, '获取成功', ['list' => []]);
        }
        $collection         = $result->getCollection();
        $order_ids          = $collection->pluck('order_id')->toArray();
        $allOrderGoods      = OrderGoods::query()->from((new OrderGoods)->getTable() . ' as og')->leftJoin("ly_goods as g", 'g.id', '=', 'og.goods_id')
            ->whereIn('og.order_id', $order_ids)->select(['og.order_id', 'g.img'])->get()->toArray();
        $allOrderGoodsGroup = [];
        if ($allOrderGoods) {
            foreach ($allOrderGoods as $v) {
                $allOrderGoodsGroup[$v['order_id']][] = $v;
            }
        }
        $collection->each(function ($item, $key) use ($allOrderGoodsGroup) {
            $orderGoods = $allOrderGoodsGroup[$item->order_id] ?? [];
            $item->img  = $orderGoods ? array_column($orderGoods, 'img') : [];
            return $item;
        });
        return Normal::returnCode(Normal::SUC, '获取成功', ['list' => $collection->toArray()]);
    }

    /**
     * 修改进货单名称
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function editHistoryOrderName(array $param) {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['history_id']) || empty($param['history_id']) || (preg_match("/^[1-9]\d*$/", (string)$param['history_id']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument history_id');
        }
        if (!isset($param['new_name']) || empty($param['new_name'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument new_name');
        }
        $orderChannel = OrderChannel::where('mid', (int)($param['mid']))->where('id', (int)($param['history_id']))->first();
        if (!$orderChannel) {
            return Normal::returnCode(Normal::FAIL, '进货单不存在');
        }
        $newName = trim($param['new_name']);
        $exist   = OrderChannel::where('mid', (int)($param['mid']))->where('id', '<>', (int)($param['history_id']))->where('name', $newName)->exists();
        if ($exist) {
            return Normal::returnCode(Normal::FAIL, '名字已被使用');
        }
        $orderChannel->name = $newName;
        $result             = $orderChannel->save();
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '修改失败');
        }
        return Normal::returnCode(Normal::SUC, '修改成功');
    }

    /**
     * 删除历史进货单
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function delHistoryOrder(array $param) {
        if (!isset($param['mid']) || empty($param['mid']) || (preg_match("/^[1-9]\d*$/", (string)$param['mid']) != 1)) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument mid');
        }
        if (!isset($param['history_id']) || empty($param['history_id'])) {
            return Normal::returnCode(Normal::FAIL, 'invalid argument history_id');
        }
        $ids = OrderChannel::where('mid', (int)($param['mid']))->whereIn('id', $param['history_id'])->pluck('id')->toArray();
        if (!$ids) {
            return Normal::returnCode(Normal::FAIL, '进货单不存在');
        }
        $result = OrderChannel::destroy($ids);
        if (!$result) {
            return Normal::returnCode(Normal::FAIL, '删除失败');
        }
        return Normal::returnCode(Normal::SUC, '删除成功');
    }

    /**
     * 渠道商品列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getChannelGoods(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }

    /**
     * 渠道商品详情
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function goodsDetail(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }

    /**
     * 提现审核列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function withdrawList(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }

    /**
     * 专题商品列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function topicGoods(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }

    /**
     * 获取首页tab页内容
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getTabContent(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }

    /**
     * 获取商品分组
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function getGoodsGroup(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }

    /**
     * 品牌商品列表
     * @param array $param 包含了系统默认参数
     * @author: hj
     */
    public function brandGoodsList(array $param) {
        return Normal::returnCode(Normal::FAIL, '待开发');
    }


}